package edu.whut.mall.portal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import edu.whut.mall.common.util.EncryptUtil;
import edu.whut.mall.common.util.HttpClientUtil;
import edu.whut.mall.common.util.WxUserOpenInfoDecodeUtil;
import edu.whut.mall.model.User;
import edu.whut.mall.portal.constant.WxMinConstant;
import edu.whut.mall.portal.service.IUserService;
import edu.whut.mall.portal.service.IWeChatService;
import edu.whut.mall.portal.vo.UserVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WeChatServiceImpl
 * @Description
 * @Author lvfanbing
 * @Date 2020-11-19 17:26
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WeChatServiceImpl implements IWeChatService {

    private final IUserService userService;

    @Override
    public String authorizationLogin(String code) {
        //        配置请求参数
        Map<String,String> params = new HashMap<>();
        params.put("appid", WxMinConstant.WX_LOGIN_APPID);
        params.put("secret", WxMinConstant.WX_LOGIN_SECRET);
        params.put("js_code", code);
        params.put("grant_type", WxMinConstant.WX_LOGIN_GRANT_TYPE);
        //        像微信服务器发送请求
        String wxRequestResult = null;
        try {
            wxRequestResult = HttpClientUtil.doGet(WxMinConstant.WX_LOGIN_URL, params);
        } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
        log.info(wxRequestResult);
        JSONObject resultJson = JSONObject.fromObject(wxRequestResult);
        if (resultJson == null) {
            return null;
        }
        String session = null;
        if (resultJson.has("openid")) {
            //        获取sessionKey和openId
            String sessionKey = resultJson.get("session_key").toString();
            String openId = resultJson.get("openid").toString();
            //        生成自定义登录态
            Map<String, String> sessionMap = new HashMap<>();
            sessionMap.put("sessionKey", sessionKey);
            sessionMap.put("openId", openId);
            session = JSONObject.fromObject(sessionMap).toString();
            try {
                EncryptUtil encryptUtil = new EncryptUtil();
                session = encryptUtil.encrypt(session);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return session;
    }

    @Override
    public UserVo getUserInfoFromWx(String encrydata, String ivdata, String session) {
        String sessionKey = null;
        String openId = null;
        try {
            EncryptUtil encryptUtil = new EncryptUtil();
            String jsonString = encryptUtil.decrypt(session);
            log.info("****decrypt String***" + jsonString);
            JSONObject jsonObject = JSONObject.fromObject(jsonString);
            sessionKey = jsonObject.getString("sessionKey");
            openId = jsonObject.getString("openId");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //      判断用户是否第一次登录
        User user = userService.selectUserByOpenId(openId);
        JSONObject userInfo = WxUserOpenInfoDecodeUtil.getUserInfo(encrydata, sessionKey, ivdata);
        if (userInfo == null) {
            return null;
        }
        User newUser = new User();
        newUser.setNickname(userInfo.getString("nickName"));
        newUser.setOpenId(openId);
        newUser.setUpdateTime(new Date());
        newUser.setPicture(userInfo.getString("avatarUrl"));
        if (user == null) {
            userService.insertUserSelective(newUser);
        } else {
            newUser.setId(user.getId());
            userService.updateUserSelective(openId, newUser);
        }
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(newUser, userVo);
        userVo.setUserId(newUser.getId());
        return userVo;
    }

    @Override
    public String getUserPhoneNumberFromWx(String encrydata, String ivdata , String session) {
        JSONObject userPhoneNumber = WxUserOpenInfoDecodeUtil.getUserInfo(encrydata, ivdata, session);
        log.info(userPhoneNumber.toString());
        return userPhoneNumber.getString("phoneNumber");
    }
}
